package com.blue.integration.config;

import com.blue.integration.spring.bean.EncryptionPropertyPlaceholderConfigurer;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.List;

/**
 * EncryptionPlaceholder 解析
 *
 * @author zhengjin
 * @since 1.0 2018年12月03日
 */
public class EncryptionPlaceholderParser extends AbstractSimpleBeanDefinitionParser
{
	public EncryptionPlaceholderParser()
	{
	}

	@Override
	protected Class<?> getBeanClass(Element element)
	{
		return EncryptionPropertyPlaceholderConfigurer.class;
	}

	@Override
	protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder)
	{
		try
		{
			List<Object> list = null;
			NodeList dictList = element.getElementsByTagNameNS("http://www.blue.com/schema/integration", "locations");
			if (dictList != null && dictList.getLength() > 0)
			{
				Element node = (Element) dictList.item(0).getChildNodes().item(1);
				list = parserContext.getDelegate().parseListElement(node, builder.getRawBeanDefinition());
			}

			String scan = element.getAttribute("location");
			if (scan != null && !scan.isEmpty())
			{
				if (list == null)
					list = new ArrayList<>();
				String[] scans = scan.split("\\s|,|;");
				for (String s : scans)
				{
					s = s.trim();
					if (s != null && !s.isEmpty())
					{
						list.add(s);
					}
				}
			}
			builder.addPropertyValue("locations", list);
		}
		catch (Exception e)
		{
			parserContext.getReaderContext().error(EncryptionPropertyPlaceholderConfigurer.class.getName() + " 无法创建", element, null, e);
		}
	}
}
